package servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Date;

import org.bson.Document;
import org.bson.types.ObjectId;
import org.json.JSONArray;

import com.mongodb.BasicDBObject;
import com.mongodb.client.MongoCursor;
import com.mongodb.util.JSON;

import mongo.CourseClass;
import mongo.Task;
import mongo.TeachingMaterialsTemplate;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@WebServlet(description = "teachingMaterialsServletProcess", urlPatterns = { "/manager/teachingMaterials/teachingMaterialsServlet" })
public class teachingMaterialsServlet extends HttpServlet{
	private Task Task = new Task();
	
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		this.doPost(request, response);
	}
	
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
	    response.setContentType("text/html;charset=UTF-8");
		
		String method = request.getParameter("method");
		if(method.equals("query")){
			this.query(request, response);
		}else if(method.equals("list")){
			this.list(request, response);
		}else{
//			request.getRequestDispatcher("404.jsp").forward(request, response); 添加错误页面
		}
	
	}
	
	public void query(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String queryname = request.getParameter("name");
    	String queryvalue = request.getParameter("value");
    	if(queryvalue.equals("")) {
    		this.list(request, response);
    	}
    	else {
    		BasicDBObject queryDBobject = new BasicDBObject(queryname,queryvalue).append("isfinish", true);
        	MongoCursor<Document> result = Task.query(queryDBobject);
        	request.setAttribute("queryname", queryname);
        	request.setAttribute("queryvalue", queryvalue);
        	request.setAttribute("result", result);
        	request.getRequestDispatcher("teachingMaterialsList.jsp").forward(request, response);
    	}
	}
	

	
	
	public void list(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
        try {
        	BasicDBObject queryDBobject = new BasicDBObject("isfinish",true);
        	MongoCursor<Document> result = Task.query(queryDBobject);
    		request.setAttribute("result", result);
    	    request.getRequestDispatcher("teachingMaterialsList.jsp").forward(request, response);
    		//response.sendRedirect("departList.jsp");
    		//TODO针对所属模块，返回到相对应的页面   
        }catch(Exception e){
            System.err.println( e.getClass().getName() + ": " + e.getMessage() );
          //TODO发生异常,跳转到对应页面
        }

	}
	
}
